<template>
	<jk-dialog
		v-model="showDialog"
		:title="`选择-项目计划`"
		width="1060px"
		append-to-body
		:confirm-btn-loading="confirmBtnLoading"
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
	>
		<div ref="box3" class="flex-center margin-bottom-10">
			<el-radio-group
				v-model="searchParams.upkeepState"
				@change="onStateChange"
			>
				<el-radio-button
					v-for="(item, index) in upkeepStateList"
					:key="index"
					:label="item.id"
				>
					<el-badge
						v-if="item.count"
						:value="item.count"
						:max="99"
					>
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<span v-else class="margin-right-10">{{ item.name }}</span>
				</el-radio-button>
			</el-radio-group>
		</div>
		<header ref="box1" class="margin-bottom-4 flex-between-center">
			<el-button size="small" type="primary" plain>
				<span>已选:</span>
				<span style="font-weight: 700;font-size: 13px;margin-right: 2px;margin-left: 4px;">{{ checkArr && checkArr.length ? checkArr.length : 0 }}</span>
				<span>个</span>
			</el-button>
			<div class="flex-start-center">
				<jk-select
					v-model="searchParams.workshopId"
					:option-list="workshopList"
					:clearable="false"
					placeholder="区域"
					size="small"
					class="search-bar-item-size2 item-gap"
				></jk-select>
				<jk-select
					v-model="searchParams.upkeepTypeIds"
					:option-list="upkeepTypeList"
					:disabled="true"
					multiple
					:collapse-tags="true"
					placeholder="保养类别"
					size="small"
					class="search-bar-item-size2 item-gap"
				></jk-select>
				<jk-select
					v-model="searchParams.processCode"
					value-key-name="code"
					:option-list="processList"
					placeholder="工序"
					clearable
					size="small"
					class="search-bar-item-size1 item-gap"
				></jk-select>
				<jk-search-input
					v-model="searchParams.machineNameOrCode"
					class="search-bar-item-size2 item-gap"
					placeholder="机台编号或名称"
					@on-search="onSearchBtn"
				></jk-search-input>
				<jk-search-input
					v-model="searchParams.upkeepItemName"
					class="search-bar-item-size2 item-gap"
					placeholder="项目名称"
					@on-search="onSearchBtn"
				></jk-search-input>
				<jk-search-button @click="onSearchBtn"></jk-search-button>
			</div>
		</header>

		<jk-table
			ref="jkTable"
			:loading="tableLoading"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			:height="dialogTableHeight - 20"
			:checkbox-config="{checkMethod: checkboxMethod}"
			@checkbox-change="selectChangeEvent"
		>
			<vxe-column type="checkbox" width="60" align="center"></vxe-column>
			<vxe-column title="机台名称" align="left" field="machineName" :width="90" />
			<vxe-column title="序号" align="center" field="sortNum" :width="60" />
			<vxe-column title="保养项目" align="left" field="upkeepItemName" :width="120" />
			<vxe-column title="保养类别" align="left" field="upkeepTypeName" :width="120" />
			<vxe-column title="计划时间" align="left" field="planUpkeepTime" :min-width="150" />
			<vxe-column title="上次时间" align="left" field="lastUpkeepTime" :min-width="150" />
			<vxe-column title="保养周期" align="left" field="cycleUnit" :width="120">
				<template slot-scope="scope">
					<span>{{ transferCircleUnit(scope.row) }}</span>
				</template>
			</vxe-column>
			<vxe-column title="计划单号" align="left" field="code" :width="150" />
		</jk-table>
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calDialogHeight from '../../../../../mixins/cal-dialog-height';
    import { pageConfig } from '../../../../../utils/jk/jk-tool';
    import { machineManagerUpkeepMachineJobPage } from '../../../../../api/machine/upkeepTask';
    import upkeepMixin from '../../upkeepItemPlan/upkeep';
    import { machineManagerUpkeepTypePage } from '../../../../../api/machine/upkeepCategory';
    import { upkeepStateList } from '../../../../../utils/jk/status-option-list';

    export default {
        mixins: [calDialogHeight, upkeepMixin],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            title: {
                type: String,
                default: '机台'
            },
            checkKeyName: {
                type: String,
                default: 'machineId'
            },
            defaultProcessName: {
                type: String,
                default: ''
            },
            upkeepTypeIds: {
                type: Array,
                default() {
                    return [];
                }
            },
            checkedData: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                upkeepStateList: upkeepStateList.filter(x => ![2, 3].includes(x.id)), // 为避免重复派工,过滤已派工和已完成的
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    processCode: '',
                    workshopId: null,
                    upkeepTypeIds: [],
                    machineNameOrCode: '',
                    upkeepState: 1,
                    upkeepItemName: '',
                    hasOptionEmp: true // 返回可选的保养人
                },
                upkeepTypeList: [],
                confirmBtnLoading: false,
                totalCount: 0,
                workshopList: [],
                processList: [],
                checkArr: [],
                selectRow: null,
                tableData: [],
                showDialog: false,
                tableLoading: false,
                selectData: []
            };
        },
        methods: {
            onStateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            selectChangeEvent({ records }) {
                this.checkArr = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            checkboxMethod(e) {
                return !e.row._disabled;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn() {
                if (this.checkArr.length) {
                    this.confirmBtnLoading = true;
                    const arr = this.checkArr.filter(x => !x._disabled);
                    this.$emit('on-confirm', arr);
                } else {
                    this.$tipsBar(this, 'custom', 'warning', '请选择数据');
                }
            },
            setCheckState(arr) {
                arr.forEach((x) => {
                    x._disabled = false;
                    this.checkedData.forEach(k => {
                        if (x.id === k[this.checkKeyName]) {
                            x._disabled = true;
                        }
                    });
                });
                this.tableData = arr;
                this.tableData.forEach((x, index) => {
                    if (x._disabled) {
                        this.$refs.jkTable.$refs.xTable.setCheckboxRow([this.tableData[index], this.tableData[index]], true);
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                this.selectData = [];
                const params = JSON.parse(JSON.stringify(this.searchParams));
                return machineManagerUpkeepMachineJobPage(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.totalCount = res.data.count;
                        this.setCheckState(res.data.res || []);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    this.confirmBtnLoading = false;
                    Object.assign(this.$data, this.$options.data());
                }
            },
            getUpkeepTypeListRequest() {
                return machineManagerUpkeepTypePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.upkeepTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList;
                this.$set(this.searchParams, 'upkeepTypeIds', this.upkeepTypeIds || []);
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
                await this.getUpkeepTypeListRequest();
                await this.getListRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
